package first.printABC;

/**
 * @ClassName PrintABC2
 * @description:
 * @author: 荣燊
 * @create: 2021-09-09 10:05
 **/
public class PrintABC2 {
    public static void main(String[] args) throws InterruptedException {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        ThreadPrint pa = new ThreadPrint("A", c, a);
        ThreadPrint pb = new ThreadPrint("B", a, b);
        ThreadPrint pc = new ThreadPrint("C", b, c);
        new Thread(pa).start();
        Thread.sleep(10);
        new Thread(pb).start();
        Thread.sleep(10);
        new Thread(pc).start();
        Thread.sleep(10);
    }

    public static class ThreadPrint implements Runnable {
        private String name;
        private Object prev;
        private Object self;

        private ThreadPrint(String name, Object prev, Object self) {
            this.name = name;
            this.prev = prev;
            this.self = self;
        }

        @Override
        public void run() {
            int count = 10;
            while (count > 0) {
                synchronized (prev) {
                    synchronized (self) {
                        System.out.print(name);
                        count--;
                        self.notifyAll();
                    }
                    try {
                        // 这一层做一个判断，如果是超过10
                        if (count == 0) {
                            prev.notifyAll();
                        } else {
                            prev.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
